<?php

namespace Hilaoyu\LaravelExtend\Services\Files\Controllers;

use Hilaoyu\LaravelExtend\ControllerBase;
use Hilaoyu\LaravelExtend\Services\Files\FileService;
use Hilaoyu\LaravelExtend\Services\Files\FilesModelAbstract;
use Hilaoyu\LaravelExtend\Supports\Uuid;
use Hilaoyu\Utils\UtilFile;
use Hilaoyu\Utils\UtilHttp;
use Hilaoyu\Utils\UtilStr;
use Hilaoyu\Utils\UtilSupport;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;


class FileViewController extends ControllerBase
{


    public function __construct()
    {
        UtilSupport::tryQuiet(function () {
            parent::__construct();
        });
    }

    /**
     * @param Request $request
     * @param $disk
     * @param $path
     * @param FilesModelAbstract $filesModel
     * @return bool|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Routing\Redirector|mixed|\Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\Response
     */

    public function view(Request $request,$disk,$path,$filesModel=null)
    {
        $width = $request->input('w',0);
        $height = $request->input('h',0);

        $real_disk = $disk;
        if($filesModel){
            $real_disk = $filesModel->getAttribute('disk');
        }
        if($client = FileService::useAsClient($real_disk)){
            $url = $client->url([
                'id'=>data_get($filesModel,'id',''),
                'path'=>$path,
            ]);

            if(!$url){
                abort(404);
            }

            return comResponse()->redirect(UtilHttp::buildUrl($url,['w'=>$width,'h'=>$height]));
        }

        //第三方文件驱动
        if('local' != FileService::getDiskConfig($disk,'driver')){
            $thumb_params = [

            ];
            $url = FileService::makeStorage($disk)->getUrl($path);

            if('cos' == FileService::getDiskConfig($disk,'driver')){
                /*
                if('public' != FileService::getDiskConfig($disk,'visibility')){
                    $expire = null;
                    $model_expire_time = data_get($filesModel,'_chche_expire_time','');
                    if($model_expire_time){
                        $expire = UtilSupport::tryQuiet(function () use ($model_expire_time){
                            return Carbon::createFromTimeString($model_expire_time)->unix();
                        });
                    }
                    if($expire<=0){
                        $temp_url_expire_time = FileService::getDiskConfig($disk,'temp_url_expire_time');
                        if($temp_url_expire_time <= 0){
                            $temp_url_expire_time = 60;
                        }

                        $expire = Carbon::now()->addMinutes($temp_url_expire_time)->unix();
                    }


                    $url = FileService::makeStorage($disk)->getAdapter()->getTemporaryUrl($path,$expire);
                }
                */
                if($width > 0 || $height > 0){
                    $thumb_string = ($width>0 ? $width :'') .'x' .($height>0 ? $height :'');
                    $thumb_params[ 'imageMogr2/thumbnail/'.$thumb_string]='';
                }

            }
            return comResponse()->redirect(UtilHttp::buildUrl($url,$thumb_params));
        }


        ob_clean();
        try {
            $Fs = new FileService($disk,$path,$filesModel);
            if($width > 0 || $height > 0){
                $Fs = $Fs->imageMakeThumb($width,$height);
            }
            $response = $Fs->response();

            if ($response) {
                //comResponse()->with($Fs,'laravel_extend_file_view_fs');
                return $response;//->send();
            }
            throw new \Exception($Fs->getError(false));
        } catch (\Exception $e) {
            throw new NotFoundHttpException('文件不存在' . $e->getMessage());
        }
    }

    public function file(Request $request,$id)
    {

        if (!$filesModel = FileService::loadFilesModel($id)) {
            abort(404);
        }


        $disk = $filesModel->getAttribute('real_disk');

        $path = $filesModel->getAttribute('path');
        if(filter_var($path,FILTER_VALIDATE_URL)){
            return comResponse()->redirect($path);
        }
        return $this->view($request,$disk,$path,$filesModel);
    }

}
